<?php

namespace app\controller\lawyer;

use app\BaseController;
use app\model\lawyer\Lawyer;
use app\model\admin\User;
use think\facade\Db;
use think\facade\Log;

/**
 * 律师用户同步控制器
 */
class LawyerSyncController extends BaseController
{
    /**
     * 同步律师到用户系统
     */
    public function syncLawyerToUser()
    {
        $lawyerId = $this->request->param('lawyer_id', 0, 'intval');
        
        if (empty($lawyerId)) {
            return json(['code' => 400, 'msg' => '律师ID不能为空']);
        }
        
        $lawyer = Lawyer::find($lawyerId);
        if (!$lawyer) {
            return json(['code' => 404, 'msg' => '律师不存在']);
        }
        
        // 使用 getter 方法访问属性
        if (!$lawyer->getAttr('can_login')) {
            return json(['code' => 403, 'msg' => '该律师不允许登录系统']);
        }
        
        // 验证用户名唯一性
        // 使用 getter 方法访问属性
        if (!$this->validateUsernameUnique($lawyer->getAttr('username'), $lawyerId)) {
            return json(['code' => 400, 'msg' => '用户名已存在，请修改律师的用户名']);
        }
        
        try {
            Db::startTrans();
            
            $adminId = $this->processLawyerSync($lawyer);
            
            Db::commit();
            
            return json(['code' => 200, 'msg' => '同步成功', 'data' => ['admin_id' => $adminId]]);
            
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('同步律师到用户系统失败：' . $e->getMessage());
            return json(['code' => 500, 'msg' => '同步失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 批量同步律师到用户系统
     */
    public function batchSyncLawyers()
    {
        $lawyerIds = $this->request->param('lawyer_ids', []);
        
        if (empty($lawyerIds)) {
            return json(['code' => 400, 'msg' => '请选择要同步的律师']);
        }
        
        $success = 0;
        $fail = 0;
        
        foreach ($lawyerIds as $lawyerId) {
            $lawyer = Lawyer::find($lawyerId);
            // 使用 getter 方法访问属性
            if (!$lawyer || !$lawyer->getAttr('can_login')) {
                $fail++;
                continue;
            }
            
            try {
                $result = $this->syncSingleLawyer($lawyer);
                if ($result) {
                    $success++;
                } else {
                    $fail++;
                }
            } catch (\Exception $e) {
                $fail++;
                Log::error("同步律师 {$lawyerId} 失败：" . $e->getMessage());
            }
        }
        
        return json([
            'code' => 200, 
            'msg' => "同步完成，成功 {$success} 个，失败 {$fail} 个",
            'data' => ['success' => $success, 'fail' => $fail]
        ]);
    }
    
    /**
     * 获取可登录的律师列表（用于同步）
     */
    public function getSyncableLawyers()
    {
        $page = $this->request->param('page', 1, 'intval');
        $limit = $this->request->param('limit', 10, 'intval');
        $keywords = $this->request->param('keywords', '');
        $firmId = $this->request->param('firm_id', 0, 'intval');
        $syncStatus = $this->request->param('sync_status', ''); // all, synced, unsynced
        
        $query = Lawyer::where('can_login', 1)
            ->where('status', 1);
            
        if ($keywords) {
            $query->where(function($q) use ($keywords) {
                $q->where('name', 'like', "%{$keywords}%")
                  ->whereOr('username', 'like', "%{$keywords}%")
                  ->whereOr('mobile', 'like', "%{$keywords}%");
            });
        }
        
        if ($firmId) {
            $query->where('firmid', $firmId);
        }
        
        if ($syncStatus === 'synced') {
            $query->where('sync_status', 1);
        } elseif ($syncStatus === 'unsynced') {
            $query->where(function($q) {
                $q->where('sync_status', 0)->whereOr('sync_status', null);
            });
        }
        
        $list = $query->page($page, $limit)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        $count = $query->count();
        
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'list' => $list,
                'count' => $count
            ]
        ]);
    }
    
    /**
     * 获取律师权限组ID
     */
    private function getLawyerGroupId()
    {
        $group = Db::name('admin_group')->where('title', '外联律师')->find();
        return $group ? $group['id'] : 1;
    }
    
    /**
     * 验证用户名唯一性
     */
    private function validateUsernameUnique($username, $excludeLawyerId = 0)
    {
        // 检查用户名是否已被其他用户使用
        $existingAdmin = User::where('username', $username)
            ->where('lawyer_id', '<>', $excludeLawyerId)
            ->find();
        
        return !$existingAdmin;
    }
    
    /**
     * 处理律师同步的核心逻辑
     */
    private function processLawyerSync($lawyer)
    {
        // 检查是否已存在对应的用户
        $admin = User::where('lawyer_id', $lawyer->getAttr('id'))->find();
        
        if ($admin) {
            // 更新现有用户
            // 使用 setter 方法设置属性
            $admin->setAttr('username', $lawyer->getAttr('username'));
            $admin->setAttr('name', $lawyer->getAttr('name'));
            $admin->setAttr('email', $lawyer->getAttr('email'));
            $admin->setAttr('mobile', $lawyer->getAttr('mobile'));
            $admin->setAttr('group_id', $this->getLawyerGroupId()); // 律师权限组
            $admin->setAttr('user_type', 2); // 外联律师
            $admin->setAttr('lawyer_id', $lawyer->getAttr('id'));
            $admin->setAttr('external_firm', $lawyer->getAttr('firm_name'));
            $admin->save();
            $adminId = $admin->getAttr('id');
        } else {
            // 创建新用户
            $admin = new User();
            // 使用 setter 方法设置属性
            $admin->setAttr('username', $lawyer->getAttr('username'));
            $admin->setAttr('pwd', password_hash('123456', PASSWORD_DEFAULT)); // 默认密码
            $admin->setAttr('name', $lawyer->getAttr('name'));
            $admin->setAttr('email', $lawyer->getAttr('email'));
            $admin->setAttr('mobile', $lawyer->getAttr('mobile'));
            $admin->setAttr('group_id', $this->getLawyerGroupId()); // 律师权限组
            $admin->setAttr('user_type', 2); // 外联律师
            $admin->setAttr('lawyer_id', $lawyer->getAttr('id'));
            $admin->setAttr('external_firm', $lawyer->getAttr('firm_name'));
            $admin->setAttr('status', 1);
            $admin->save();
            $adminId = $admin->getAttr('id');
        }
        
        // 更新律师表的关联ID
        // 使用 setter 方法设置属性
        $lawyer->setAttr('admin_id', $adminId);
        $lawyer->setAttr('sync_status', 1);
        $lawyer->save();
        
        return $adminId;
    }
    
    /**
     * 同步单个律师
     */
    private function syncSingleLawyer($lawyer)
    {
        try {
            // 验证用户名唯一性
            // 使用 getter 方法访问属性
            if (!$this->validateUsernameUnique($lawyer->getAttr('username'), $lawyer->getAttr('id'))) {
                Log::error("同步律师 {$lawyer->getAttr('id')} 失败：用户名 {$lawyer->getAttr('username')} 已存在");
                return false;
            }
            
            $this->processLawyerSync($lawyer);
            return true;
        } catch (\Exception $e) {
            // 使用 getter 方法访问属性
            Log::error("同步律师 {$lawyer->getAttr('id')} 失败：" . $e->getMessage());
            return false;
        }
    }
}